Page({
  data: {
    searchValue: '',
    showStoreInfo: true, // 控制门店信息条是否显示
    storeInfo: {
      name: "奶茶总店",
      address: "星城路368号",
      phone: "18812345678"
    },
    categories: [
      { id: 0, name: "人气TOP" },
      { id: 1, name: "奶茶系列" },
      { id: 2, name: "果茶系列" },
      { id: 3, name: "芝士系列" },
      { id: 4, name: "小吃系列" },
      { id: 5, name: "甜品系列" }
    ],
    products: [
      {
        categoryId: 0,
        items: [
          { id: 101, name: "招牌奶茶", desc: "传统手工制作", price: 18, sales: 232, imageUrl: "/images/products/product1.jpg" },
          { id: 102, name: "芝芝芒果", desc: "清新芒果配芝士", price: 22, sales: 188, imageUrl: "/images/products/product2.jpg" },
          { id: 103, name: "多肉葡萄", desc: "多种水果搭配", price: 20, sales: 120, imageUrl: "/images/products/product3.jpg" }
        ]
      },
      {
        categoryId: 1,
        items: [
          { id: 104, name: "烤奶", desc: "香浓奶香回味", price: 19, sales: 166, imageUrl: "/images/products/product4.jpg" },
          { id: 105, name: "波波奶茶", desc: "珍珠与奶茶的完美结合", price: 18, sales: 155, imageUrl: "/images/products/product1.jpg" },
          { id: 106, name: "黑糖奶茶", desc: "黑糖与奶茶的碰撞", price: 20, sales: 143, imageUrl: "/images/products/product4.jpg" }
        ]
      },
      {
        categoryId: 2,
        items: [
          { id: 107, name: "满杯红柚", desc: "新鲜红柚肉", price: 22, sales: 125, imageUrl: "/images/products/product5.jpg" },
          { id: 108, name: "芒果果茶", desc: "清新芒果口感", price: 21, sales: 132, imageUrl: "/images/products/product2.jpg" },
          { id: 109, name: "满杯橙子", desc: "维C充沛", price: 23, sales: 112, imageUrl: "/images/products/product5.jpg" }
        ]
      },
      {
        categoryId: 3,
        items: [
          { id: 110, name: "芝士奶盖奶茶", desc: "浓郁奶盖", price: 21, sales: 145, imageUrl: "/images/products/product3.jpg", tag: "热门" },
          { id: 111, name: "芝士奶盖绿茶", desc: "清爽绿茶", price: 20, sales: 134, imageUrl: "/images/products/product6.jpg" },
          { id: 112, name: "芝士草莓", desc: "草莓融芝士", price: 25, sales: 120, imageUrl: "/images/products/product5.jpg" }
        ]
      },
      {
        categoryId: 4,
        items: [
          { id: 113, name: "盐酥鸡", desc: "外酥里嫩", price: 18, sales: 208, imageUrl: "/images/products/product4.jpg" },
          { id: 114, name: "薯条", desc: "香脆可口", price: 16, sales: 195, imageUrl: "/images/products/product1.jpg" },
          { id: 115, name: "鸡米花", desc: "香辣多汁", price: 17, sales: 176, imageUrl: "/images/products/product3.jpg" }
        ]
      },
      {
        categoryId: 5,
        items: [
          { id: 116, name: "草莓波波", desc: "新鲜草莓搭配珍珠", price: 23, sales: 102, imageUrl: "/images/products/product5.jpg", tag: "新品" },
          { id: 117, name: "芒果双皮奶", desc: "顺滑双皮奶", price: 20, sales: 98, imageUrl: "/images/products/product2.jpg" },
          { id: 118, name: "抹茶蛋糕", desc: "松软可口", price: 22, sales: 87, imageUrl: "/images/products/product6.jpg" }
        ]
      }
    ],
    activeCategory: 0,
    scrollIntoView: 'category0',
    cartCount: 0,
    cart: [],
    showCartDetail: false, // 控制购物车小框是否显示
    addedProduct: null, // 刚添加的商品信息
    categoryTops: [] // 存储每个分类的顶部位置
  },

  onLoad: function (options) {
    try {
      // 从缓存中获取购物车数据
      const cartList = wx.getStorageSync('cartList') || [];

      // 确保cartList是数组
      if (!Array.isArray(cartList)) {
        console.error('购物车数据不是数组，正在重置');
        wx.setStorageSync('cartList', []);
        this.setData({
          cart: [],
          cartCount: 0
        });
        return;
      }

      // 确保购物车中的每个商品都有quantity属性
      const validCartList = cartList.filter(item =>
        item && typeof item === 'object' && item.id && typeof item.quantity === 'number'
      );

      // 如果有无效商品，更新存储
      if (validCartList.length !== cartList.length) {
        wx.setStorageSync('cartList', validCartList);
      }

      // 安全计算总数量
      const totalQuantity = validCartList.reduce((total, item) => {
        return total + (item && typeof item.quantity === 'number' ? item.quantity : 0);
      }, 0);

      this.setData({
        cart: validCartList,
        cartCount: totalQuantity
      });

      // 计算每个分类的顶部位置（用于滚动定位）
      this.calculateCategoryTops();
    } catch (error) {
      console.error('onLoad error:', error);
      // 出错时设置默认值
      this.setData({
        cart: [],
        cartCount: 0
      });
    }
  },

  onShow: function () {
    try {
      // 每次显示页面时更新购物车数据
      const cartList = wx.getStorageSync('cartList') || [];
      this.setData({
        cart: cartList,
        cartCount: cartList.reduce((total, item) => total + (item && item.quantity ? item.quantity : 0), 0)
      });
    } catch (error) {
      console.error('onShow error:', error);
    }
  },

  // 搜索输入处理
  onSearch: function (e) {
    this.setData({
      searchValue: e.detail.value
    });
    // 可以在这里实现实时搜索功能
  },

  // 清除搜索内容
  clearSearch: function () {
    this.setData({
      searchValue: ''
    });
  },

  // 切换分类
  switchCategory: function (e) {
    const categoryId = e.currentTarget.dataset.id;
    this.setData({
      activeCategory: categoryId,
      scrollIntoView: 'category' + categoryId
    });
  },

  // 滚动处理
  handleScroll: function (e) {
    const scrollTop = e.detail.scrollTop;
    const categoryTops = this.data.categoryTops || [];

    // 根据滚动位置判断当前是哪个分类
    for (let i = categoryTops.length - 1; i >= 0; i--) {
      if (scrollTop >= categoryTops[i].top - 10) { // 减去一个偏移值，使体验更好
        if (this.data.activeCategory !== categoryTops[i].id) {
          this.setData({
            activeCategory: categoryTops[i].id
          });
        }
        break;
      }
    }
  },

  // 计算各分类区域的顶部位置
  calculateCategoryTops: function () {
    const query = wx.createSelectorQuery();
    query.selectAll('.category-title').boundingClientRect(rects => {
      const categoryTops = rects.map(rect => {
        return {
          id: parseInt(rect.id.replace('category', '')),
          top: rect.top
        };
      });
      this.setData({ categoryTops: categoryTops });
    }).exec();
  },

  // 跳转到商品详情
  toDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}&from=in-store`
    });
  },

  // 添加到购物车
  addToCart: function (e) {
    try {
      const { id, name, price, imageurl } = e.currentTarget.dataset;

      // 构建商品信息
      const productInfo = {
        id: parseInt(id),
        name: name || '',
        price: parseFloat(price) || 0,
        image: imageurl || '/images/products/default.jpg',
        quantity: 1,
        itemTotal: parseFloat(price) || 0
      };

      // 获取购物车
      const cartList = [...(this.data.cart || [])];
      let found = false;
      let updatedProduct = null;

      // 查找购物车中是否已有该商品
      if (cartList && cartList.length > 0) {
        for (let i = 0; i < cartList.length; i++) {
          if (cartList[i] && cartList[i].id === parseInt(id)) {
            found = true;
            cartList[i].quantity = (cartList[i].quantity || 0) + 1;
            cartList[i].itemTotal = cartList[i].quantity * parseFloat(price || 0);
            updatedProduct = cartList[i];
            break;
          }
        }
      }

      // 如果购物车中没有该商品，则添加
      if (!found) {
        cartList.push(productInfo);
        updatedProduct = productInfo;
      }

      // 计算购物车总数量
      const cartCount = cartList.reduce((total, item) =>
        total + (item && typeof item.quantity === 'number' ? item.quantity : 0), 0);

      // 更新数据
      this.setData({
        cart: cartList,
        cartCount: cartCount,
        addedProduct: updatedProduct,
        showCartDetail: true
      });

      // 保存到本地存储
      wx.setStorageSync('cartList', cartList);

      // 3秒后隐藏购物车小框
      setTimeout(() => {
        this.setData({
          showCartDetail: false
        });
      }, 3000);

    } catch (error) {
      console.error('添加到购物车出错:', error);
      wx.showToast({
        title: '添加失败，请重试',
        icon: 'none'
      });
    }
  },

  // 跳转到购物车页面
  toCart: function () {
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },

  // 更新小框中商品数量
  updateQuantity: function (e) {
    const { operation } = e.currentTarget.dataset;
    const { addedProduct, cart } = this.data;

    if (!addedProduct) return;

    let quantity = addedProduct.quantity;

    if (operation === 'add') {
      quantity += 1;
    } else if (operation === 'minus') {
      if (quantity <= 1) return;
      quantity -= 1;
    }

    // 更新购物车中的商品数量
    const newCart = cart.map(item => {
      if (item.id === parseInt(addedProduct.id)) {
        const updatedItem = { ...item, quantity };
        // 重新计算总价
        updatedItem.itemTotal = updatedItem.price * updatedItem.quantity;
        return updatedItem;
      }
      return item;
    });

    this.setData({
      cart: newCart,
      cartCount: newCart.reduce((total, item) => total + item.quantity, 0),
      'addedProduct.quantity': quantity
    });

    // 保存到本地存储
    wx.setStorageSync('cartList', newCart);
  },

  // 关闭购物车小框
  closeCartDetail: function () {
    this.setData({
      showCartDetail: false
    });
  },

  // 关闭门店信息条
  closeStoreInfo: function () {
    this.setData({
      showStoreInfo: false
    });
  },

  // 停止事件冒泡
  stopPropagation: function (e) {
    // 用于阻止点击事件冒泡
  },

  // 更新购物车函数
  updateCart: function (cartItem) {
    try {
      // 从存储中获取当前购物车
      let cartList = wx.getStorageSync('cartList') || [];

      // 确保cartList是数组
      if (!Array.isArray(cartList)) {
        cartList = [];
      }

      // 防止空对象
      if (!cartItem || typeof cartItem !== 'object' || !cartItem.id) {
        console.error('无效的购物车项', cartItem);
        return false;
      }

      // 查找是否已存在该商品
      const index = cartList.findIndex(item =>
        item && item.id === cartItem.id
      );

      if (index > -1) {
        // 已存在则更新数量
        cartList[index].quantity = (cartList[index].quantity || 0) + (cartItem.quantity || 1);
      } else {
        // 不存在则添加
        cartList.push(cartItem);
      }

      // 保存回存储
      wx.setStorageSync('cartList', cartList);

      // 安全计算购物车总数量
      const cartCount = cartList.reduce((total, item) => {
        return total + (item && typeof item.quantity === 'number' ? item.quantity : 0);
      }, 0);

      // 更新页面数据
      this.setData({
        cart: cartList,
        cartCount: cartCount
      });

      return true;
    } catch (error) {
      console.error('更新购物车出错:', error);
      return false;
    }
  }
}) 